/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.database.dao.impl;

import com.database.dao.CargoDao;
import com.database.model.Cargo;
import com.database.util.HibernateUtil;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.hibernate.Session;

/**
 *
 * @author diego y Yinna
 */
public class CargoDaoImplement implements CargoDao{

    @Override
    public List<Cargo> buscarTodos() {
        Session session= HibernateUtil.getSessionFactory().openSession();
        return session.createQuery("from Cargo cargo order by cargo.nombre asc").list();
    }

    @Override
    public void insertar(Cargo cargo) {
        Session session= HibernateUtil.getSessionFactory().openSession();
         FacesContext context = FacesContext.getCurrentInstance();   
         try{
             session.beginTransaction();
             session.save(cargo);
             session.beginTransaction().commit();
             context.addMessage(null, new FacesMessage("Se el cargo "+cargo.getNombre()+" con éxito!")); 
         }catch(Exception e){
             context.addMessage(null, new FacesMessage("Hubo un problema al guardar "+e.getMessage())); 
             session.beginTransaction().rollback();
         }
    }

    @Override
    public void actualizar(Cargo cargo) {
         Session session= HibernateUtil.getSessionFactory().openSession();
          FacesContext context = FacesContext.getCurrentInstance();   
         try{
             session.beginTransaction();
             session.merge(cargo);
             session.beginTransaction().commit(); 
             context.addMessage(null, new FacesMessage("Se ha actualizado "+cargo.getNombre()+" con éxito!")); 
         }catch(Exception e){
             context.addMessage(null, new FacesMessage("Hubo un problema al actualizar: "+e.getMessage())); 
             session.beginTransaction().rollback();
         }
    }

    @Override
    public void eliminar(Cargo cargo) {
        Session session= HibernateUtil.getSessionFactory().openSession();
        FacesContext context = FacesContext.getCurrentInstance();   
         try{
             session.beginTransaction();
             session.delete(cargo);
             session.beginTransaction().commit();
             context.addMessage(null, new FacesMessage("Se ha eliminado "+cargo.getNombre()+" con éxito!")); 
         }catch(Exception e){
             context.addMessage(null, new FacesMessage("Hubo un problema al eliminar:  "+e.getMessage())); 
             session.beginTransaction().rollback();
         }
    }

    @Override
    public Cargo buscarPorId(Integer id) {
       Session session= HibernateUtil.getSessionFactory().openSession();
          return (Cargo) session.load(Cargo.class, id);
    }
    
}
